package com.elite.groovy.callback

import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.kh.LogToDB
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
 * @projectName: ngsapi_cs
 * @package: cn.com.callback
 * @className: apiQWSendMSG
 * @author: LiJT
 * @description: 企微原生消息发送API
 * @date: 2022-12-19 14:03
 * @version: 1.0
 */
public class apiQWSendMSG implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiQWSendMSG.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();

        JSONObject resultJson = new JSONObject();
        resultJson.put("errcode", 0);
        resultJson.put("errmsg", "");
        resultJson.put("msgid", "");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn("API被非法IP调用-Request Not Allow!");
            resultJson.put("errcode", -2);
            resultJson.put("errmsg", "API被非法IP调用-Request Not Allow!");
            return resultJson.toString();
        }

        // 获取数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        //接收客户端调用参数
        String callInfo = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callInfo += line;
        }
        log.info("[调用请求信息]:" + callInfo);

        try {
            JSONObject callJson = JSONObject.fromObject(callInfo);

            if (callJson.has("staffid")) {
                String staffid = callJson.getString("staffid");
                String content = callJson.getString("content");

                // 查询staff对应的企微信息
                String selectSQL = '''Select Device_Id From Staff Where Staff_Id = ?''';
                List<Map<String, Object>> selectResult = jt.queryForList(selectSQL, staffid);
                log.debug("查询staff对应的企微信息Result:" + selectResult.toString());

                if (selectResult.size() > 0) {
                    String touser = selectResult.get(0).get("Device_Id").toString();
                    log.debug("查询staff对应的企微信息touser:" + touser);

                    if (!KHUtil.isNull(touser) && !KHUtil.isNull(content)) {

                        resultJson = sendQW(eliteBean, touser, content);
                    } else {
                        resultJson.put("errcode", -3);
                        resultJson.put("errmsg", "未查询到Staff对应的企微ID,或发送消息内容为空");

                    }
                } else {
                    resultJson.put("errcode", -3);
                    resultJson.put("errmsg", "未查询到Staff信息");

                }
            } else if (!callJson.has("agentid")) {

                String touser = callJson.getString("touser");
                String content = callJson.getString("content");
                if (!KHUtil.isNull(touser) && !KHUtil.isNull(content)) {

                    resultJson = sendQW(eliteBean, touser, content);
                } else {
                    resultJson.put("errcode", -3);
                    resultJson.put("errmsg", "touser为空,或发送消息内容为空");

                }
            } else {
                // 无发送人信息-将转发请求
                resultJson = sendQW(eliteBean, callInfo);
            }


        } catch (Exception e) {
            log.error("接口处理异常", e);
            resultJson.put("errcode", -1);
            resultJson.put("errmsg", "接口处理异常" + e.getMessage());

        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "发送企微消息[内部]", "apiQWSendMSG", callInfo, resultJson.toString(), (System.currentTimeMillis() - startTime).toString(), getMethod);
        }

        return resultJson.toString();
    }

    public static JSONObject sendQW(EliteBean eliteBean, String touser, String content) throws Exception {

        // 获取企微Token
        JSONObject getTokenJson = JSONObject.fromObject(Util.doHttpGet(KHDBConfig.getAPIURL(eliteBean, "SYS-InnerDomain") + "groovy/GeneralService/apiGetToken?appid=WXG_DAVCO", "UTF-8", 12000, 0));
        String access_token = getTokenJson.getJSONObject("value").getString("access_token");
        log.debug("获取调用Token:" + access_token);

        // 发送消息
        JSONObject sendJson = new JSONObject();
        sendJson.put("agentid", KHDBConfig.getParamConfig(eliteBean, "QW_AgentID"));
        sendJson.put("touser", touser);
        sendJson.put("msgtype", "text");

        JSONObject textJson = new JSONObject();
        textJson.put("content", content);
        sendJson.put("text", textJson);
        sendJson.put("safe", 0);
        sendJson.put("enable_id_trans", 0);
        sendJson.put("enable_duplicate_check", 0);
        log.debug("发送企业微信消息请求体:" + sendJson.toString());

        String sendResult = Util.doHttpPost("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token, sendJson.toString(), "UTF-8", 120000, 0);
        log.debug("发送企业微信消息返回:" + sendResult);

        return JSONObject.fromObject(sendResult);

    }

    public static JSONObject sendQW(EliteBean eliteBean, String content) throws Exception {

        // 获取企微Token
        JSONObject getTokenJson = JSONObject.fromObject(Util.doHttpGet(KHDBConfig.getAPIURL(eliteBean, "SYS-InnerDomain") + "groovy/GeneralService/apiGetToken?appid=WXG_DAVCO", "UTF-8", 12000, 0));
        String access_token = getTokenJson.getJSONObject("value").getString("access_token");
        log.debug("获取调用Token:" + access_token);

        // 发送消息
        JSONObject sendJson = JSONObject.fromObject(content);
        log.debug("发送企业微信消息请求体:" + sendJson.toString());

        String sendResult = Util.doHttpPost("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token, sendJson.toString(), "UTF-8", 120000, 0);
        log.debug("发送企业微信消息返回:" + sendResult);

        return JSONObject.fromObject(sendResult);

    }
}